<?php

namespace App\Admin\Controllers;

use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use App\Models\Goods;
use App\Models\Setting;
use App\Admin\Actions\Goods\ImportGoods;

class GoodsController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '商品列表';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Goods);

        $grid->column('id', __('ID'))->sortable();
        $grid->column('goods_bn', '货号');
        $grid->column('goods_name', '商品名称');
        $grid->column('goods_alias', '商品简称')->editable();
        $grid->column('sale_price', '合作价(元)')->editable();
        // $grid->column('cost_price', '成本价(元)')->editable();
        $grid->column('euro_cost_price', '成本价(欧元/人民币)')->display(function($euro_cost_price){
            $rate_euro = Setting::get('rate_euro');
            $rmb_price = number_format($this->euro_cost_price * $rate_euro['value'], 2);
            return $this->euro_cost_price ." / ".$rmb_price;
        })->editable();
        $grid->column('created_at', __('创建时间'))->sortable();
        $grid->column('updated_at', __('更新时间'))->sortable();

        $grid->filter(function($filter) {

            // 去掉默认的id过滤器
            $filter->disableIdFilter();

            // 在这里添加字段过滤器
            $filter->like('goods_bn', '货号');
            $filter->like('goods_name', '商品名称');
        });

        $grid->tools(function (Grid\Tools $tools) {
            $tools->append(new ImportGoods());
        });

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed   $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Goods::findOrFail($id));

        $show->field('id', __('商品ID'));
        $show->field('goods_bn', '商品货号');
        $show->field('goods_name', '商品名称');
        $show->field('goods_alias', '商品简称');
        $show->field('sale_price', '商品售价');
        $show->field('cost_price', '成本价');
        $show->field('created_at', __('创建时间'));
        $show->field('updated_at', __('更新时间'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Goods);

        $form->display('id', __('商品ID'));
        $form->text('goods_bn', '商品货号')->rules('required');
        $form->text('goods_name', '商品名称')->rules('required');
        $form->text('goods_alias', '商品简称');
        $form->text('sale_price', '商品售价');
        $form->text('cost_price', '成本价');
        $form->text('euro_cost_price', '成本价(欧元)');
        $form->display('created_at', __('创建时间'));
        $form->display('updated_at', __('更新时间'));

        return $form;
    }
}
